#include "newuserdialog.h"
#include "ui_newuserdialog.h"

#include <QRegExpValidator>
#include <QMessageBox>
#include <QPushButton>
#include <QDebug>

NewUserDialog::NewUserDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewUserDialog)
{
    ui->setupUi(this);
	setModal( true );
	setWindowModality( Qt::ApplicationModal );

	QRegExpValidator *validator = new QRegExpValidator( ui->userName );
	validator->setRegExp( QRegExp("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$",
						  Qt::CaseInsensitive) );
	ui->userName->setValidator( validator );

	connect( ui->buttonBox, SIGNAL(accepted()),
			 this, SLOT(validateData()) );
	ui->buttonBox->button( QDialogButtonBox::Cancel )->setDefault( true );

}

NewUserDialog::~NewUserDialog(){
    delete ui;
}

void NewUserDialog::validateData(){
	if( ui->userName->text().isEmpty() ||
		 ui->password->text().isEmpty() ||
		 ui->password2->text().isEmpty() )
	{
		QMessageBox::warning( this, tr("Ostrzeżenie"),
							  tr("Pola nie mogą być puste") );
		return;
	}


	const QValidator *val = ui->userName->validator();
	QString text = ui->userName->text();
	int pos = 0;
	if( QValidator::Acceptable != val->validate( text, pos ) ){
		QMessageBox::warning( this, tr("Ostrzeżenie"),
							  tr("Nazwa użytkownika nie jest poprawnym adresem"
								 " email") );
		return;
	}

	if( ui->password->text() != ui->password2->text() ){
		QMessageBox::warning( this, tr("Ostrzeżenie"),
							  tr("Podane hasła nie są identyczne") );
		return;
	}

	accept();
}
